<?php
require_once("MyNumber.php");
$db = mysqli_connect("localhost","root","","urlshort");
function setUser($user,$userid){
	if($user != ""){
		setcookie("user", ($user."--".$userid), time() + (86400*30*365), "/");
	}else{
		setcookie("user", "", time()-1, "/");
	}
}
function user($field){
	//field : 0 for no or 1 for uname
	return explode("--",$_COOKIE["user"])[$field];
}
function logged(){
	return isset($_COOKIE["user"]) && $_COOKIE["user"] != "";
}
function getShortUrl($urlSum,$id){
	//creates short url from the sum of 20 url characters, +the id of current url (auto increment)
	$urlId = new MyNumber($id);
	$urlShort = $urlSum."".$urlId;
	$res = base_url()."?u=".$urlShort;
	$res = substr($res,strpos($res,"//")+2);
	return $res;
}
function getFullUrl($u){
	global $db;
	//retrieve the full url from short url
	//get the first 2 character first, for verification
	$xx = substr($u,0,2);
	//then get the MyNumber id
	$yy = MyNumber::toDec(substr($u,2));
	//check in the database, whether the id and xx matches
	$que = mysqli_query($db,"select fullurl from urltable where id=$yy and link='$xx'");
	if(mysqli_num_rows($que) > 0){
		return mysqli_fetch_assoc($que)["fullurl"];
	}else{
		return "";
	}
}

if(!function_exists('base_url')) {
	function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
		if (isset($_SERVER['HTTP_HOST'])) {
			$http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
			$hostname = $_SERVER['HTTP_HOST'];
			$dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

			$core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
			$core = $core[0];

			$tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
			$end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
			$base_url = sprintf( $tmplt, $http, $hostname, $end );
		}
		else $base_url = 'http://localhost/';
			if ($parse) {
			$base_url = parse_url($base_url);
			if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
		}
		return $base_url;
	}
}
?>

